<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="../common/style/reset.css" />
    <style>
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .swiper-box {
        width: 100%;
        height: 100%;
        background-image: url("../components/IconSvg/image.svg");
        background-size: 100% 100%;
        background-position: center;
        background-repeat: no-repeat;
        position: relative;
      }

      .swiper-box img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        opacity: 0;
        transition: opacity 0.8s;
      }
    </style>
  </head>
  <body>
    <div class="swiper-box">
      <!-- <img src="../components/IconSvg/image.svg" alt=""> -->
    </div>
  </body>
  <script type="module" src="../common/js/setting.js"></script>
  <script type="module" src="../common/js/menu.js"></script>
  <script type="module" src="../common/js/move.js"></script>
  <script type="module" src="../common/js/counter.js"></script>
  <script type="module">
    import UpTimer from "./resetData.js";

    // const img = document.querySelector("img");
    const swiperBoxEl = document.querySelector(".swiper-box");
    const rightMenuEl = document.querySelector(".right-menu");
    let imgsEl;

    let data = {
      delay: 1 * 60 * 1000,
      urls: [],
      switch: false,
      num: 0,
    };
    let timer = null,
      pastTime;


    window.removeImgBuffer = () => {
      if(!data.urls.length)return
      data.urls.forEach((item, index) => {
        window.utools.dbStorage.removeItem(item)
      });
    } 

    if (window.ipcRenderer) {
      window.ipcRenderer.on("sendData", async (event, res) => {
        // if(data.switch && res.switch === false){ data.num ? data.num-- : data.num = res.urls.length - 1 }
        if(!res.num && !(res.switch === true && data.switch === false) )
        {data.num ? data.num-- : data.num = res.urls.length - 1}
        else if(res.switch === true && data.switch === false){
          
        }else{
          data.num = 0
        }
        data.delay =
          res.delay != 0 && res.delay === false ? data.delay : res.delay;
        data.switch = res.switch;
        if(res.urls.length){
          window.removeImgBuffer();
          data.urls = res.urls;
          let buffer64s = await bufferData(res.urls)
          render(buffer64s);
        }else{
          delays();
        }
        window.sendSaveData(data);
      });

      window.ipcRenderer.on("init", (event, res) => {
        data = { ...data, ...res };
        let buffer64s = getBuffers()
        render(buffer64s);
      });
    }

    const bufferData = async (files) => {
      let buffer64s = []
      for(let index in files){
        let item = files[index]
        let [fileName, extension] = window.pathParse(item)
        let imageBuffer = await window.readFile(item)
        const base64Image = imageBuffer.toString('base64');
        window.utools.db.postAttachment(item, imageBuffer, `image/${extension}`)
        
        buffer64s.push({
          base64Image,
          name: fileName,
          extension: `image/${extension}`
        })
      }
      return buffer64s;
    }

    const getBuffers = () => {
     return data.urls.map(item=>{
      let imageBuffer = utools.db.getAttachment(item)
      let extension = utools.db.getAttachmentType(item)
      let buffer = window.toBuffer(imageBuffer)
      let base64Image = buffer.toString('base64');
      return {
        base64Image,
        extension
      }
     })
    }

    const delays = () => {
      imgsEl = document.querySelectorAll(".swiper-box img");
      cancelAnimationFrame(timer);
      // clearInterval(timer);
      timer = null;
      if (data.delay && data.switch && imgsEl?.length) {
        pastTime = null;
        let upTimer = new UpTimer(data.delay);
        swiperBoxEl.style.backgroundImage = "none";
        step(upTimer);
      } else if (!data.switch && data.urls.length) {
        swiperBoxEl.style.backgroundImage = "none";
        imgsEl[data.num].style.opacity = 1;
      } else {
        swiperBoxEl.style.backgroundImage = `url('../components/IconSvg/image.svg')`;
      }
    };

    const step = (upTimer) => {
      timer = requestAnimationFrame(() => {
        if (pastTime !== upTimer.delayTime()) {
          imgsEl.forEach((item, index) => {
            if (index === data.num) {
              item.style.opacity = 1;
            } else {
              item.style.opacity = 0;
            }
          });
          window.sendSaveData(data);
          pastTime = upTimer.delayTime();
          data.num++;
          if (data.num >= imgsEl.length) {
            data.num = 0;
          }
        }

        step(upTimer);
      });
    };

    // const step1 = (upTimer) => {
    //   timer = setInterval(()=>{
    //     if (pastTime !== upTimer.delayTime()) {
    //       imgsEl.forEach((item, index) => {
    //         if (index === data.num) {
    //           item.style.opacity = 1;
    //         } else {
    //           item.style.opacity = 0;
    //         }
    //       });
    //       window.sendSaveData(data);
    //       pastTime = upTimer.delayTime();
    //       data.num++;
    //       if (data.num >= imgsEl.length) {
    //         data.num = 0;
    //       }
    //     }
    //   },1000)
    // }




    const render = (base64s) => {
      let html = "";
      if (data.urls.length) {
        base64s.forEach((item, index) => {
          html += `<img src="data:${item.extension};base64,${item.base64Image}" alt="">`;
        });
      }

      swiperBoxEl.innerHTML = html;

      delays();
    };


    window.getData = () => {
      return data;
    };
  </script>
</html>
